﻿using System.Web;
using TSB.SharePointUrlShortener.DAL;

namespace TSB.SharePointUrlShortener.Handlers
{
    public class TSBUrlShortenerHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            var shortUrl = string.Empty;
            var found = false;
            foreach(var urlPart in context.Request.Url.AbsolutePath.Split('/'))
            {
                if (found)
                {
                    shortUrl = urlPart;
                    break;
                }
                if (urlPart == "url")
                {
                    found = true;
                }
            }
            
            var urlShortenerRepository = new UrlShortenerRepository();

            var redirectUrl = urlShortenerRepository.GetRedirectFromShortcode(shortUrl);

            if (!string.IsNullOrEmpty(redirectUrl))
            {
                context.Response.Redirect(redirectUrl);
            }
        }

        public bool IsReusable
        {
            get { return true; }
        }
    }
}
